package com.xzt.transaction.controller;

import com.xzt.transaction.service.LogInfoService;
import com.xzt.transaction.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOError;
import java.io.IOException;

@Slf4j
@RequestMapping("/user2")
@RestController
public class UserInfoController2 {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private LogInfoService logInfoService;

    @Transactional
    @RequestMapping("/registry")
    public String registry(String name, String password) {
        //⽤⼾注册
        userInfoService.registryUser(name, password);
        log.info("用户数据插入成功");
        try {
            int a=10/0;
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return "注册成功";
    }

    @Transactional(rollbackFor = IOException.class)
    @RequestMapping("/test1")
    public String test1(String name, String password) throws IOException{
        //⽤⼾注册
        userInfoService.registryUser(name, password);
        log.info("用户数据插入成功");
        if (true){
            throw new IOException();
        }
        return "注册成功";
    }

    @Transactional
    @RequestMapping("/test2")
    public String test2(String name, String password){
        //⽤⼾注册
        Integer result = userInfoService.registryUser(name, password);
        log.info("用户数据插入成功,影响行数："+result);
        Integer logResult = logInfoService.insertLog(name, "用户注册");
        log.info("日志记录成功, 影响行数:" + logResult);
        return "注册成功";
    }
}
